﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Helena.Areas.Entradas.Models;
using Helena.Areas.Vendedores.Models;
using Helena.Areas.Productos.Models;
using Helena.Areas.Ventas.Models;
using Helena.Areas.Salidas.Models;
using System.IO;
using System.Text;
using Helena.Areas.Categorias.Models;
using Helena.Areas.Campanas.Models;
using Helena.Areas.Configuraciones.Models;
using Helena.Areas.Degustaciones.Models;
using Helena.Areas.Clientes.Models;

namespace Helena.Areas.Reportes.Controllers
{
    public class VariosController : Controller
    {
        LogicaEntrada entradas = new LogicaEntrada();
        LogicaCliente clientes = new LogicaCliente();
        LogicaVenta ventas = new LogicaVenta();
        LogicaSalida salidas = new LogicaSalida();
        LogicaVendedor vendedor = new LogicaVendedor();
        LogicaProducto producto = new LogicaProducto();
        LogicaCategoria categoria = new LogicaCategoria();
        LogicaCampana campana = new LogicaCampana();
        LogicaUnidad unidad = new LogicaUnidad();
        LogicaDegustacion degustaciones = new LogicaDegustacion();
        LogicaTarjeta tarj = new LogicaTarjeta();

        //
        // GET: /Reportes/Varios/

        public ActionResult Index()
        {
            VendedorView vw = (VendedorView)Session["Vendedor"];
            if (vw.ID != 0)
            {
                return View();
            }
            else
            {
                return Redirect("../../Home/NoSession");
            }
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Ventas()
        {
            VendedorView vw = (VendedorView)Session["Vendedor"];
            try
            {
                if (vw.ID != 0)
                {
                    List<VentaView> v = new List<VentaView>();
                    v.Add(new VentaView());
                    Session["_detalle"] = string.Empty;
                    return View(v);
                }
                else
                {
                    return Redirect("../../Home/NoSession");
                }
            }
            catch
            {
                return Redirect("../../Home/Error");
            }

        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Ventas(DateTime fecha)
        {
            List<VentaView> lventas = new List<VentaView>();
            lventas = ventas.i_RetornarVentas().Where(e => e.Fecha.DayOfYear == fecha.DayOfYear).Where(e=>e.Estado ==true).ToList();

            String salida = String.Empty;

            foreach (VentaView ev in lventas)
            {
                string aux = " ";
                if (ev.Descripcion == null)
                {
                    aux = "Venta Correcta";
                }
                else
                {
                    aux = ev.Descripcion;
                }
                //tarj.i_RetornarTarjeta(ev.tarjetaID).Descripcion + "¬" +
                salida += ev.ID.ToString() + "¬" +
                          ev.Ticket.ToString() + "¬" +
                          ev.Boleta.ToString() + "¬" +
                          ev.Factura.ToString() + "¬" +
                          clientes.i_RetornarCliente(ev.ClienteID).RazonSocial + "¬" +
                          vendedor.i_RetornarVendedro(ev.VendedorID).NombreLargo + "¬" +
                          "S/. " + ev.Sub_Total.ToString() + "¬" +
                          ev.Descuento.ToString() + " %" + "¬" +
                          "S/. " + ev.Total_En_Soles.ToString() + "¬"+
                          "US$ " + ev.Total_En_Dolares.ToString() + "¬" +
                          "S/. " + ev.Valor_Del_Igv_En_Soles.ToString() + "¬" +
                          "S/. "+ ev.ValorTipoCambio.ToString()+ "¬" +
                          "S/. " + ev.Pago_en_Efectivo_en_Soles.ToString() + "¬" +
                          "S/. " + ev.Pago_con_Tarjeta_en_Soles.ToString() + "¬" +
                          "US$/. " + ev.Pago_en_Efectivo_en_Dolares.ToString() + "¬" +
                          "S/. " + Convert.ToString((ev.Vuelto)) + " ° ";

                List<DetalleVentaView> detalles = ventas.DetallesDeUnaVenta(ev.ID);

                foreach (DetalleVentaView dvv in detalles)
                {
                    salida += producto.i_RetornarProducto(dvv.ProductoID).Descripcion + "|" + dvv.Cantidad.ToString() + "|" + "S/. " + dvv.PrecioU.ToString() +"|" +
                        "S/. " + dvv.Igv_del_Subtotal + "|" +"S/. " + dvv.Subtotal.ToString() + "|~";
                }
                salida += "^";
            }
            Session["_detalle"] = salida;
            Session["Fecha"] = new DateTime(fecha.Year, fecha.Month, fecha.Day);
            List<VentaView> ex = new List<VentaView>();
            ex.Add(new VentaView());
            return View(ex);
        }


        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Entradas()
        {
            VendedorView vw = (VendedorView)Session["Vendedor"];
            try
            {
                if (vw.ID != 0)
                {
                    List<EntradaView> e = new List<EntradaView>();
                    e.Add(new EntradaView());
                    Session["_detalle"] = string.Empty;
                    return View(e);
                }
                else
                {
                    return Redirect("../../Home/NoSession");
                }
            }
            catch
            {
                return Redirect("../../Home/Error");
            }

        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Entradas(DateTime fecha)
        {
            List<EntradaView> entrada = new List<EntradaView>();
            entrada = entradas.i_RetornarEntradas().Where(e => e.Fecha.DayOfYear == fecha.DayOfYear).ToList();

            String salida = String.Empty;

            foreach (EntradaView ev in entrada)
            {
                salida += ev.NumeroGuia + "¬" + ev.NumeroFactura + "¬" +
                           vendedor.i_RetornarVendedro(ev.VendedorID).NombreLargo + "¬" +
                           ev.Descripcion + "°";
                List<DetalleEntradaView> detalles = entradas.DetallesDeUnaEntrada(ev.ID);

                foreach (DetalleEntradaView dvv in detalles)
                {
                    salida += producto.i_RetornarProducto(dvv.ProductoID).Descripcion + "|" +
                              dvv.Cantidad + "|~";
                }
                salida += "^";
            }
            Session["_detalle"] = salida;
            Session["Fecha"] = new DateTime(fecha.Year, fecha.Month, fecha.Day);
            List<EntradaView> ex = new List<EntradaView>();
            ex.Add(new EntradaView());
            return View(ex);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Salidas()
        {
            VendedorView vw = (VendedorView)Session["Vendedor"];
            try
            {
                if (vw.ID != 0)
                {

                    List<SalidaView> e = new List<SalidaView>();
                    e.Add(new SalidaView());
                    Session["_detalle"] = string.Empty;
                    return View(e);
                }
                else
                {
                    return Redirect("../../Home/NoSession");
                }
            }
            catch
            {
                return Redirect("../../Home/Error");
            }

        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Salidas(DateTime fecha)
        {
            List<SalidaView> entrada = new List<SalidaView>();
            entrada = salidas.i_RetornarSalidas().Where(e => e.Fecha.DayOfYear == fecha.DayOfYear).ToList();

            String salida = String.Empty;

            foreach (SalidaView ev in entrada)
            {
                salida += ev.NumeroGuia + "¬" +
                           vendedor.i_RetornarVendedro(ev.VendedorID).NombreLargo + "¬" +
                           ev.Descripcion + "°";
                List<DetalleSalidaView> detalles = salidas.DetallesDeUnaSalida(ev.ID);

                foreach (DetalleSalidaView dvv in detalles)
                {
                    salida += producto.i_RetornarProducto(dvv.ProductoID).Descripcion + "|" +
                              dvv.Cantidad + "|~";
                }
                salida += "^";
            }
            Session["_detalle"] = salida;
            Session["Fecha"] = new DateTime(fecha.Year, fecha.Month, fecha.Day);
            List<SalidaView> ex = new List<SalidaView>();
            ex.Add(new SalidaView());
            return View(ex);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Degustaciones()
        {
            VendedorView vw = (VendedorView)Session["Vendedor"];
            try
            {
                if (vw.ID != 0)
                {
                    List<DegustacionView> e = new List<DegustacionView>();
                    e.Add(new DegustacionView());
                    Session["_detalle"] = string.Empty;
                    return View(e);
                }
                else
                {
                    return Redirect("../../Home/NoSession");
                }
            }
            catch
            {
                return Redirect("../../Home/Error");
            }


        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Degustaciones(DateTime fecha)
        {
            string salida = string.Empty; ;
            List<DegustacionView> degus = degustaciones.i_RetornarDegustaciones().Where(d => d.Estado == true).ToList();

            foreach (DegustacionView d in degus)
            {
                salida += vendedor.i_RetornarVendedro(d.VendedorID).NombreLargo + "¬";
                salida += producto.i_RetornarProducto(d.ProductoID).Descripcion + "¬";
                salida += categoria.i_RetornarCategoria(d.CategoriaID).NombreCategoria + "¬";
                salida += campana.i_RetornarCampana(d.CampanaID).NombreCampana + "¬";
                salida += d.Cantidad + "¬";
                salida += d.Descripcion + "¬";
                salida += "°";
            }

            Session["_detalle"] = salida;
            Session["Fecha"] = new DateTime(fecha.Year, fecha.Month, fecha.Day);
            List<DegustacionView> e = new List<DegustacionView>();
            e.Add(new DegustacionView());
            return View(e);
        }

        public ActionResult ExportarExceDegustaciones()
        {
            MemoryStream output = new MemoryStream();
            StreamWriter writer = new StreamWriter(output, Encoding.UTF8);

            string salida = Session["_detalle"].ToString();

            writer.Write("Vendedor");
            writer.Write(",");
            writer.Write("Categoria");
            writer.Write(",");
            writer.Write("Campaña");
            writer.Write(",");
            writer.Write("Producto Degustado");
            writer.Write(",");
            writer.Write("Cantidad");
            writer.Write(",");
            writer.Write("Descripcion");
            writer.Write(",");
            writer.WriteLine();

            string[] sal = salida.Split('°');
            foreach (string s in sal)
            {
                string[] sux = s.Split('¬');
                foreach (string x in sux)
                {
                    writer.Write(x);
                    writer.Write(",");
                }
                writer.WriteLine();
            }
            writer.Flush();
            output.Position = 0;

            return File(output, "text/comma-separated-values", "Degustacion_" + ((DateTime)Session["Fecha"]).ToShortDateString() + ".csv");
        }

        public ActionResult ExportarExcelEntradas()
        {

            string detalles = Session["_detalle"].ToString();

            MemoryStream output = new MemoryStream();
            StreamWriter writer = new StreamWriter(output, Encoding.UTF8);

            writer.Write("NumeroGuia");
            writer.Write(",");
            writer.Write("NumeroFactura");
            writer.Write(",");
            writer.Write("Vendedor");
            writer.Write(",");
            writer.Write("Descripcion");
            writer.Write(",");
            writer.Write(" ");
            writer.Write(",");
            writer.Write(" ");
            writer.WriteLine();

            foreach (string entrada in detalles.Split('^'))
            {
                if (entrada != "")
                {
                    string[] linea = entrada.Split('°');
                    string[] entradalinea = linea[0].Split('¬');
                    string[] detallelinea = linea[1].Split('~');

                    writer.Write(entradalinea[0]);
                    writer.Write(",");
                    writer.Write(entradalinea[1]);
                    writer.Write(",");
                    writer.Write(entradalinea[2]);
                    writer.Write(",");
                    writer.Write(entradalinea[3]);
                    writer.Write(",");
                    writer.Write("Descripcion");
                    writer.Write(",");
                    writer.Write("Cantidad");
                    writer.Write(" ");
                    writer.WriteLine();

                    foreach (string lineas in detallelinea)
                    {
                        if (lineas != "")
                        {
                            string[] s = lineas.Split('|');
                            writer.Write(" ");
                            writer.Write(",");
                            writer.Write(" ");
                            writer.Write(",");
                            writer.Write(" ");
                            writer.Write(",");
                            writer.Write(" ");
                            writer.Write(",");
                            writer.Write(s[0]);
                            writer.Write(",");
                            writer.Write(s[1]);
                            writer.Write(" ");
                            writer.WriteLine();
                        }
                    }
                }
            }

            writer.Flush();
            output.Position = 0;

            return File(output, "text/comma-separated-values", "Entradas_" + ((DateTime)Session["Fecha"]).ToShortDateString() + ".csv");
        }

        public ActionResult ExportarExcelSalidas()
        {
            string detalles = Session["_detalle"].ToString();

            MemoryStream output = new MemoryStream();
            StreamWriter writer = new StreamWriter(output, Encoding.UTF8);

            writer.Write("NumeroGuia");
            writer.Write(",");
            writer.Write("Vendedor");
            writer.Write(",");
            writer.Write("Descripcion");
            writer.Write(",");
            writer.Write(" ");
            writer.Write(",");
            writer.Write(" ");
            writer.WriteLine();

            foreach (string entrada in detalles.Split('^'))
            {
                if (entrada != "")
                {
                    string[] linea = entrada.Split('°');
                    string[] entradalinea = linea[0].Split('¬');
                    string[] detallelinea = linea[1].Split('~');

                    writer.Write(entradalinea[0]);
                    writer.Write(",");
                    writer.Write(entradalinea[1]);
                    writer.Write(",");
                    writer.Write(entradalinea[2]);
                    writer.Write(",");
                    writer.Write("Descripcion");
                    writer.Write(",");
                    writer.Write("Cantidad");
                    writer.Write(" ");
                    writer.WriteLine();

                    foreach (string lineas in detallelinea)
                    {
                        if (lineas != "")
                        {
                            string[] s = lineas.Split('|');
                            writer.Write(" ");
                            writer.Write(",");
                            writer.Write(" ");
                            writer.Write(",");
                            writer.Write(" ");
                            writer.Write(",");
                            writer.Write(s[0]);
                            writer.Write(",");
                            writer.Write(s[1]);
                            writer.Write(" ");
                            writer.WriteLine();
                        }
                    }
                }
            }

            writer.Flush();
            output.Position = 0;

            return File(output, "text/comma-separated-values", "Salidas_" + ((DateTime)Session["Fecha"]).ToShortDateString() + ".csv");
        }

        public ActionResult ExportarExcelVentas()
        {

            string detalles = Session["_detalle"].ToString();

            MemoryStream output = new MemoryStream();
            StreamWriter writer = new StreamWriter(output, Encoding.UTF8);

            writer.Write("IDVenta");
            writer.Write(",");
            writer.Write("Nro Ticket");
            writer.Write(",");
            writer.Write("Nro Boleta");
            writer.Write(",");
            writer.Write("Nro Factura");
            writer.Write(",");
            writer.Write("Cliente");
            writer.Write(",");
            writer.Write("Vendedor");
            writer.Write(",");
            writer.Write("Sub Total S/.");
            writer.Write(",");
            writer.Write("Descuento %");
            writer.Write(",");
            writer.Write("Total S/");
            writer.Write(",");
            writer.Write("Total US$");
            writer.Write(",");
            writer.Write("IGV S/.");
            writer.Write(",");
            writer.Write("Tipo Cambio");
            writer.Write(",");
            writer.Write("Pago en Efectivo S/.");
            writer.Write(",");
            writer.Write("Pago en Tarjeta S/.");
            writer.Write(",");
            writer.Write("Pago en Dolares US$");
            writer.Write(",");
            writer.Write("Vuelto S/.");
            writer.Write(",");
            writer.WriteLine();

            foreach (string entrada in detalles.Split('^'))
            {
                if (entrada != "")
                {
                    string[] linea = entrada.Split('°');
                    string[] entradalinea = linea[0].Split('¬');
                    string[] detallelinea = linea[1].Split('~');

                    foreach (string s in entradalinea)
                    {
                        writer.Write(s);
                        writer.Write(",");
                    }
                    
                    writer.Write(" ");
                    writer.WriteLine();
                    writer.Write(" ");
                    writer.Write(",");
                    writer.Write(" ");
                    writer.Write(",");
                    writer.Write(" ");
                    writer.Write(",");
                    writer.Write(" ");
                    writer.Write(",");
                    writer.Write(" ");
                    writer.Write(",");
                    writer.Write(" ");
                    writer.Write(",");
                    writer.Write(" ");
                    writer.Write(",");
                    writer.Write(" ");
                    writer.Write(",");
                    writer.Write(" ");
                    writer.Write(",");
                    writer.Write(" ");
                    writer.Write(",");
                    writer.Write(" ");
                    writer.Write(",");
                    writer.Write(" ");
                    writer.Write(",");
                    writer.Write(" ");
                    writer.Write(",");
                    writer.Write(" ");
                    writer.Write(",");
                    writer.Write(" ");
                    writer.Write(",");
                    writer.Write(" ");
                    writer.Write(",");
                    writer.Write("Productos");
                    writer.Write(",");
                    writer.Write("Cantidad");
                    writer.Write(",");
                    writer.Write("PrecioU");
                    writer.Write(",");
                    writer.Write("IGV");
                    writer.Write(",");
                    writer.Write("SubTotal");
                    writer.Write(" ");
                    writer.WriteLine();


                    foreach (string lineas in detallelinea)
                    {
                        if (lineas.Length>3)
                        {
                            string[] s = lineas.Split('|');
                            writer.Write(" ");
                            writer.Write(",");
                            writer.Write(" ");
                            writer.Write(",");
                            writer.Write(" ");
                            writer.Write(",");
                            writer.Write(" ");
                            writer.Write(",");
                            writer.Write(" ");
                            writer.Write(",");
                            writer.Write(" ");
                            writer.Write(",");
                            writer.Write(" ");
                            writer.Write(",");
                            writer.Write(" ");
                            writer.Write(",");
                            writer.Write(" ");
                            writer.Write(",");
                            writer.Write(" ");
                            writer.Write(",");
                            writer.Write(" ");
                            writer.Write(",");
                            writer.Write(" ");
                            writer.Write(",");
                            writer.Write(" ");
                            writer.Write(",");
                            writer.Write(" ");
                            writer.Write(",");
                            writer.Write(" ");
                            writer.Write(",");
                            writer.Write(" ");
                            writer.Write(",");
                            writer.Write(s[0]);
                            writer.Write(",");
                            writer.Write(s[1]);
                            writer.Write(",");
                            writer.Write(s[2]);
                            writer.Write(",");
                            writer.Write(s[3]);
                            writer.Write(",");
                            writer.Write(s[4]);
                            writer.Write(" ");
                            writer.WriteLine();
                        }
                    }
                }
            }

            writer.Flush();
            output.Position = 0;

            return File(output, "text/comma-separated-values", "Ventas_" + ((DateTime)Session["Fecha"]).ToShortDateString() + ".csv");
        }
    }
}
